using FytSoa.Application.Erp.Param;
using FytSoa.Common.Enum;
using FytSoa.Common.Extensions;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using FytSoa.Domain;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-生产订单工艺路线关系表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpProduceOrderCraftService : IApplicationService 
{
    private readonly SugarRepository<ErpProduceOrderCraft> _thisRepository;
    private readonly ErpOperateLogService _operateLogService;
    public ErpProduceOrderCraftService(SugarRepository<ErpProduceOrderCraft> thisRepository
    ,ErpOperateLogService operateLogService)
    {
        _thisRepository = thisRepository;
        _operateLogService = operateLogService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpProduceOrderCraftDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpProduceOrderCraftDto>>();
    }
    
    /// <summary>
    /// 查询所有
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpProduceOrderCraftDto>> GetListAsync(ErpOrderCraftSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id != 0, m => m.OrderId == param.Id)
            .WhereIF(param.Type==1,m=>m.PersonId==AppUtils.EmployeeId)
            .WhereIF(param.Reject==1,m=>m.IsReject)
            .WhereIF(param.Reject==0,m=>!m.IsReject)
            .WhereIF(param.ProductId!=0,m=>m.ProductId==param.ProductId)
            .WhereIF(!string.IsNullOrEmpty(param.Status),m=>m.Status==int.Parse(param.Status))
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>
                SqlFunc.Subqueryable<ErpProduceCraft>().Where(c=>c.Id==m.CraftId && c.Name.Contains(param.Key)).Any())
            .WhereIF(param.Phase!=0,m=>
                SqlFunc.Subqueryable<ErpProduceOrder>().Where(o=>o.Id==m.OrderId && o.Phase==param.Phase).Any())
            .WhereIF(param.Audit!=0,m=>
                SqlFunc.Subqueryable<ErpProduceOrder>().Where(o=>o.Id==m.OrderId && o.Status==param.Audit).Any())
            .Includes(m=>m.Employee)
            .Includes(m=>m.Craft)
            .Includes(m=>m.Order,o=>o.Project)
            .Includes(m=>m.Product)
            .OrderBy(m => m.Number)
            .ToListAsync();
        return query.Adapt<List<ErpProduceOrderCraftDto>>();
    }

    /// <summary>
    /// 查询所有
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<SelectBase>> GetSelectAsync(ErpOrderCraftSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id != 0, m => m.OrderId == param.Id)
            .WhereIF(param.Type==1,m=>m.PersonId==AppUtils.EmployeeId)
            .WhereIF(param.Reject==1,m=>m.IsReject)
            .WhereIF(param.Reject==0,m=>!m.IsReject)
            .WhereIF(param.ProductId!=0,m=>m.ProductId==param.ProductId)
            .WhereIF(!string.IsNullOrEmpty(param.Status),m=>m.Status==int.Parse(param.Status))
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>
                SqlFunc.Subqueryable<ErpProduceCraft>().Where(c=>c.Id==m.CraftId && c.Name.Contains(param.Key)).Any())
            .WhereIF(param.Phase!=0,m=>
                SqlFunc.Subqueryable<ErpProduceOrder>().Where(o=>o.Id==m.OrderId && o.Phase==param.Phase).Any())
            .WhereIF(param.Audit!=0,m=>
                SqlFunc.Subqueryable<ErpProduceOrder>().Where(o=>o.Id==m.OrderId && o.Status==param.Audit).Any())
            .GroupBy(m=>m.ProductId)
            .Select(m=>m.ProductId)
            .ToListAsync();
        var productRepository = _thisRepository.ChangeRepository<SugarRepository<ErpProduct>>();
        var productList = await productRepository.GetListAsync(m => query.Contains(m.Id));
        var list = new List<SelectBase>();
        foreach (var item in productList)
        {
            list.Add(new SelectBase()
            {
                Label = item.Name,
                Value = item.Id.ToString(),
            });
        }

        return list;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpProduceOrderCraftDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.Employee)
            .Includes(m=>m.Craft)
            .Includes(m=>m.Order,o=>o.Project)
            .Includes(m=>m.Product)
            .SingleAsync(m => m.Id == id);
        return model.Adapt<ErpProduceOrderCraftDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task AddAsync(ErpProduceOrderCraftDto model)
    {
        /*var isAny = await _thisRepository.IsAnyAsync(m =>
            m.OrderId == model.OrderId && m.CraftId == model.CraftId && m.ProductId == model.ProductId);
        if (isAny)
        {
            throw new BusinessException("已存在相同的工艺流程~");
        }*/

        var after = await _thisRepository.GetByIdAsync(model.AfterId);
        if (after==null)
        {
            throw new BusinessException("您选择插入后面的工艺流程不存在~");
        }
        var list = await _thisRepository.AsQueryable()
            .Where(m => m.Number > after.Number)
            .OrderBy(m=>m.Number)
            .ToListAsync();
       
        model.Number = after.Number + 1;
        await _thisRepository.InsertAsync(model.Adapt<ErpProduceOrderCraft>());

        foreach (var item in list)
        {
            item.Number = model.Number += 1;
        }

        await _thisRepository.AsUpdateable(list)
            .UpdateColumns(it => new {it.Number})
            .ExecuteCommandAsync();
        //await _thisRepository.UpdateRangeAsync(list);
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ErpProduceOrderCraftDto model) =>
        await _thisRepository.UpdateAsync(model.Adapt<ErpProduceOrderCraft>());

    /// <summary>
    /// 拖拽修改
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task ModifyDragAsync(List<long> ids)
    {
        var index = 0;
        var upSql = string.Empty;
        foreach (var item in ids)
        {
            index++;
            upSql += "update erp_produce_order_craft set number="+index+" where id="+item+";";
        }

        await _thisRepository.Context.Ado.ExecuteCommandAsync(upSql);
    }

    /// <summary>
    /// 更改任务节点状态
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyStatusAsync(ErpOrderCraftStatusParam param)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.Craft)
            .SingleAsync(m=>m.Id==param.Id);

        if (model.Status+1!=param.Status && !model.IsReject)
        {
            throw new BusinessException("请按步骤完成流程！");
        }
        if (model.Status>=param.Status)
        {
            throw new BusinessException("状态变更不能回退！");
        }
        if (param.Status==(int)ErpProduceStatusEnum.Completed && model.StatusProcess.Count>0)
        {
            //计算工时
            var timeDifference = DateTime.Now - model.StatusProcess.Last().Time; 
            model.WorkHour = Math.Round(timeDifference.TotalHours,1); 
        }
        model.StatusProcess.Add(new ErpProduceOrder.DesignProcessModel.ProcessModel()
        {
            Status = param.Status,
            EmployeeName = AppUtils.LoginUser,
            EmployeeId = AppUtils.EmployeeId
        });
        model.Status = param.Status;
        await _thisRepository.UpdateAsync(model);

        var statusVal = param.Status switch
        {
            0 => "待接收",
            1 => "已接收",
            2 => "已开工",
            3 => "已完成",
            _ => string.Empty
        };
        
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateId = model.OrderId,
            Type = (int)ErpOperateEnum.ProduceOrder,
            Remark = "生产订单，变更了工艺流程【"+model.Craft.Name+"】状态为："+statusVal+""
        });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
